<template>
  <div class="message-center-container">
    <el-card class="message-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <h2 class="card-title">
              <el-icon class="title-icon"><Message /></el-icon>
              消息中心
              <el-badge :value="unreadCount" :max="99" class="unread-badge" v-if="unreadCount > 0" />
            </h2>
            <el-tag type="info" class="message-count">共 {{ messages.length }} 条消息</el-tag>
          </div>
          <div class="search-container">
            <el-input 
              v-model="searchKeyword" 
              placeholder="搜索消息标题、发件人或内容..." 
              class="search-input"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button 
              type="primary" 
              @click="handleSearch" 
              class="search-button"
              :icon="Search"
            >
              搜索
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="message-tabs">
        <el-tabs v-model="activeTab" class="message-filter-tabs">
          <el-tab-pane label="全部消息" name="all"></el-tab-pane>
          <el-tab-pane label="未读消息" name="unread"></el-tab-pane>
          <el-tab-pane label="系统消息" name="system"></el-tab-pane>
          <el-tab-pane label="交易消息" name="transaction"></el-tab-pane>
        </el-tabs>
      </div>
      
      <div class="message-list">
        <el-empty description="暂无消息" v-if="filteredMessages.length === 0" />
        
        <div 
          v-for="message in filteredMessages"
          :key="message.id"
          class="single-message-card"
          :class="{'unread': !message.isRead, 'selected': selectedMessageId === message.id}"
          @click="showMessageDetail(message)"
        >
          <div class="message-avatar">
            <el-avatar :size="40" :src="message.avatar || getDefaultAvatar(message.sender)" />
          </div>
          <div class="message-content">
            <div class="message-header">
              <div class="message-title">
                <span class="title-text">{{ message.title }}</span>
                <el-tag 
                  v-if="!message.isRead" 
                  type="danger" 
                  size="small"
                  effect="light"
                  class="unread-tag"
                >
                  未读
                </el-tag>
                <el-tag 
                  v-if="message.important" 
                  type="danger" 
                  size="small"
                  effect="light"
                  class="important-tag"
                >
                  重要
                </el-tag>
              </div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
            <div class="message-sender">
              <el-icon><User /></el-icon>
              {{ message.sender }}
            </div>
            <div class="message-preview">{{ message.preview }}</div>
          </div>
        </div>
      </div>
      
      <div class="pagination-container" v-if="filteredMessages.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredMessages.length"
        />
      </div>
    </el-card>

    <el-dialog 
      v-model="isMessageDetailVisible" 
      :title="currentMessage.title"
      width="60%"
      class="message-detail-dialog"
    >
      <div class="message-detail">
        <div class="detail-header">
          <div class="sender-info">
            <el-avatar :size="50" :src="currentMessage.avatar || getDefaultAvatar(currentMessage.sender)" />
            <div class="sender-text">
              <div class="sender-name">{{ currentMessage.sender }}</div>
              <div class="send-time">{{ formatDetailTime(currentMessage.timestamp) }}</div>
            </div>
          </div>
          <div class="message-actions">
            <el-button 
              type="danger" 
              plain 
              size="small" 
              v-if="currentMessage.important"
              @click="toggleImportant(currentMessage)"
            >
              <el-icon><StarFilled /></el-icon>
              取消标记重要
            </el-button>
            <el-button 
              type="warning" 
              plain 
              size="small" 
              v-else
              @click="toggleImportant(currentMessage)"
            >
              <el-icon><Star /></el-icon>
              标记为重要
            </el-button>
            <el-button type="danger" plain size="small" @click="deleteMessage(currentMessage)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </div>
        
        <div class="detail-content">
          <div class="content-text">{{ currentMessage.content }}</div>
          <div class="attachments" v-if="currentMessage.attachments && currentMessage.attachments.length > 0">
            <div class="attachments-title">附件：</div>
            <div class="attachment-list">
              <div 
                v-for="(file, index) in currentMessage.attachments" 
                :key="index" 
                class="attachment-item"
              >
                <el-icon><Document /></el-icon>
                {{ file.name }} ({{ formatFileSize(file.size) }})
                <el-button type="text" @click="downloadAttachment(file)">下载</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="replyMessage(currentMessage)" type="primary" plain>
            <el-icon><Position /></el-icon>
            回复
          </el-button>
          <el-button @click="forwardMessage(currentMessage)" plain>
            <el-icon><Share /></el-icon>
            转发
          </el-button>
          <el-button @click="isMessageDetailVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { 
  Search, 
  Message, 
  User, 
  Star, 
  StarFilled, 
  Delete, 
  Document,
  Position,
  Share
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

// 模拟消息数据
const messages = ref([
  {
    id: 1,
    title: '系统维护通知',
    sender: '系统管理员',
    timestamp: new Date('2025-05-14T10:00:00'),
    preview: '系统将于今晚23:00-24:00进行维护升级，请提前保存您的工作...',
    content: '尊敬的各位用户：\n\n为了提供更好的服务体验，我们计划于2025年5月14日23:00至24:00进行系统维护升级。在此期间，系统将暂时无法访问。\n\n请提前安排好您的工作，避免在维护期间进行重要操作。维护完成后，系统将自动恢复服务。\n\n感谢您的理解与支持！\n\n系统运维团队',
    isRead: false,
    important: true,
    type: 'system',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    attachments: [
      { name: '维护计划.pdf', size: 2456789 },
      { name: '升级内容说明.docx', size: 123456 }
    ]
  },
  {
    id: 2,
    title: '您的订单已发货',
    sender: '商城客服',
    timestamp: new Date('2025-05-13T15:30:00'),
    preview: '您购买的商品已发货，物流单号：SF123456789，预计3个工作日内送达...',
    content: '尊敬的顾客：\n\n您于2025年5月12日下单的商品已发货。\n\n物流公司：顺丰速运\n物流单号：SF123456789\n\n预计送达时间：3个工作日内\n\n您可以通过我们的网站或物流公司官网跟踪您的包裹。如有任何问题，请联系我们的客服。\n\n感谢您的惠顾！\n\n商城客服团队',
    isRead: true,
    important: false,
    type: 'transaction',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  },
  {
    id: 3,
    title: '账户安全提醒',
    sender: '安全中心',
    timestamp: new Date('2025-05-12T09:15:00'),
    preview: '检测到您的账户在异地登录，如果不是您本人操作，请立即修改密码...',
    content: '尊敬的用户：\n\n我们的系统检测到您的账户于2025年5月12日09:15从新的设备(IP: 123.123.123.123 位置: 北京市)登录。\n\n如果这不是您本人的操作，建议您立即：\n1. 修改账户密码\n2. 启用双重验证\n3. 检查账户安全设置\n\n如您有任何疑问，请联系我们的安全团队。\n\n安全中心',
    isRead: false,
    important: true,
    type: 'system',
    avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'
  },
  {
    id: 4,
    title: '交易成功通知',
    sender: '支付平台',
    timestamp: new Date('2025-05-10T14:20:00'),
    preview: '您的订单(编号: 20250510123456)已支付成功，金额: ¥256.00...',
    content: '尊敬的客户：\n\n您的订单(编号: 20250510123456)已支付成功。\n\n支付金额：¥256.00\n支付时间：2025年5月10日 14:20:35\n支付方式：支付宝\n\n您可以在"我的订单"中查看订单详情。如有任何问题，请联系我们的客服。\n\n感谢您的使用！\n\n支付平台',
    isRead: true,
    important: false,
    type: 'transaction',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
  }
]);

const searchKeyword = ref('');
const isMessageDetailVisible = ref(false);
const currentMessage = ref({});
const activeTab = ref('all');
const currentPage = ref(1);
const pageSize = ref(10);
const selectedMessageId = ref(null);

const unreadCount = computed(() => {
  return messages.value.filter(msg => !msg.isRead).length;
});

const filteredMessages = computed(() => {
  let result = messages.value;
  
  // 按标签筛选
  if (activeTab.value !== 'all') {
    result = result.filter(msg => {
      if (activeTab.value === 'unread') return !msg.isRead;
      if (activeTab.value === 'system') return msg.type === 'system';
      if (activeTab.value === 'transaction') return msg.type === 'transaction';
      return true;
    });
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    result = result.filter(msg => {
      return (
        msg.title.toLowerCase().includes(keyword) ||
        msg.sender.toLowerCase().includes(keyword) ||
        msg.preview.toLowerCase().includes(keyword) ||
        msg.content.toLowerCase().includes(keyword)
      );
    });
  }
  
  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return result.slice(start, end);
});

const handleSearch = () => {
  currentPage.value = 1;
  ElMessage.success(`找到 ${filteredMessages.value.length} 条相关消息`);
};

const showMessageDetail = (message) => {
  selectedMessageId.value = message.id;
  currentMessage.value = {...message};
  // 标记为已读
  if (!currentMessage.value.isRead) {
    const msg = messages.value.find(m => m.id === message.id);
    if (msg) msg.isRead = true;
  }
  isMessageDetailVisible.value = true;
};

const formatTime = (timestamp) => {
  const now = new Date();
  const time = new Date(timestamp);
  const diffHours = Math.floor((now - time) / (1000 * 60 * 60));

  if (diffHours < 1) {
    const diffMinutes = Math.floor((now - time) / (1000 * 60));
    return diffMinutes < 1 ? '刚刚' : `${diffMinutes}分钟前`;
  } else if (diffHours < 24) {
    return `${diffHours}小时前`;
  } else {
    return time.toLocaleDateString();
  }
};

const formatDetailTime = (timestamp) => {
  const time = new Date(timestamp);
  return time.toLocaleString();
};

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]);
};

const getDefaultAvatar = (sender) => {
  // 根据发件人返回不同的默认头像
  const colors = ['#FF6B6B', '#48D597', '#4D96FF', '#6C5CE7'];
  const index = sender.length % colors.length;
  return `https://via.placeholder.com/40/${colors[index].substring(1)}/FFFFFF?text=${sender.charAt(0)}`;
};

const toggleImportant = (message) => {
  const msg = messages.value.find(m => m.id === message.id);
  if (msg) {
    msg.important = !msg.important;
    ElMessage.success(msg.important ? '已标记为重要消息' : '已取消重要标记');
  }
};

const deleteMessage = (message) => {
  messages.value = messages.value.filter(m => m.id !== message.id);
  isMessageDetailVisible.value = false;
  ElMessage.success('消息已删除');
};

const downloadAttachment = (file) => {
  ElMessage.info(`开始下载: ${file.name}`);
  // 实际项目中这里应该是调用下载API
};

const replyMessage = (message) => {
  ElMessage.info(`回复消息给: ${message.sender}`);
  isMessageDetailVisible.value = false;
};

const forwardMessage = (message) => {
  ElMessage.info(`转发消息: ${message.title}`);
  isMessageDetailVisible.value = false;
};

onMounted(() => {
  // 页面加载时的逻辑
});
</script>

<style scoped lang="scss">
.message-center-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: 100vh;
  padding: 40px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
}

.message-card {
  width: 100%;
  max-width: 900px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  transition: all 0.3s cubic-bezier(0.25, 0, 0.25, 1);
  border: none;
  background-color: rgba(255, 255, 255, 0.95);
  
  &:hover {
    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.12);
  }
}

.card-header {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
  }
  
  .search-container {
    display: flex;
    gap: 10px;
  }
}

.card-title {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
  
  .title-icon {
    color: #4D96FF;
  }
  
  .unread-badge {
    margin-left: 8px;
  }
}

.message-count {
  font-size: 0.8rem;
  border-radius: 12px;
}

.search-input {
  flex: 1;
  
  :deep(.el-input__wrapper) {
    border-radius: 12px;
    padding-left: 12px;
  }
}

.search-button {
  border-radius: 12px;
  padding: 0 20px;
}

.message-tabs {
  padding: 0 20px;
  border-bottom: 1px solid #f0f0f0;
  
  :deep(.el-tabs__header) {
    margin: 0;
  }
  
  :deep(.el-tabs__nav-wrap::after) {
    height: 1px;
    background-color: #f0f0f0;
  }
  
  :deep(.el-tabs__item) {
    padding: 0 16px;
    height: 40px;
    font-size: 14px;
  }
}

.message-list {
  padding: 0;
  min-height: 400px;
}

.single-message-card {
  display: flex;
  gap: 16px;
  padding: 16px 20px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  transition: all 0.2s ease;
  
  &:hover {
    background-color: #f9f9f9;
  }
  
  &.unread {
    background-color: #f0f7ff;
    
    &:hover {
      background-color: #e6f0ff;
    }
  }
  
  &.selected {
    background-color: #e6f0ff;
    border-left: 3px solid #4D96FF;
  }
  
  .message-avatar {
    flex-shrink: 0;
  }
  
  .message-content {
    flex: 1;
    overflow: hidden;
  }
  
  .message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }
  
  .message-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    display: flex;
    align-items: center;
    gap: 8px;
    overflow: hidden;
    
    .title-text {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
  
  .message-time {
    font-size: 12px;
    color: #999;
    flex-shrink: 0;
    margin-left: 8px;
  }
  
  .message-sender {
    font-size: 13px;
    color: #666;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    gap: 4px;
  }
  
  .message-preview {
    font-size: 14px;
    color: #666;
    line-height: 1.5;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .unread-tag {
    margin-left: 8px;
  }
  
  .important-tag {
    margin-left: 8px;
  }
}

.pagination-container {
  padding: 20px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #f0f0f0;
}

.message-detail-dialog {
  :deep(.el-dialog__header) {
    border-bottom: 1px solid #f0f0f0;
    margin-right: 0;
  }
  
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.message-detail {
  padding: 20px;
  
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 16px;
    
    .sender-info {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .sender-text {
        .sender-name {
          font-weight: 600;
          margin-bottom: 4px;
        }
        
        .send-time {
          font-size: 12px;
          color: #999;
        }
      }
    }
    
    .message-actions {
      display: flex;
      gap: 8px;
    }
  }
  
  .detail-content {
    .content-text {
      white-space: pre-line;
      line-height: 1.8;
      margin-bottom: 20px;
    }
    
    .attachments {
      margin-top: 20px;
      padding-top: 16px;
      border-top: 1px dashed #eee;
      
      .attachments-title {
        font-weight: 600;
        margin-bottom: 8px;
      }
      
      .attachment-list {
        .attachment-item {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 8px 12px;
          background-color: #f9f9f9;
          border-radius: 6px;
          margin-bottom: 8px;
          font-size: 14px;
          
          &:hover {
            background-color: #f0f0f0;
          }
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
}

@media (max-width: 768px) {
  .message-center-container {
    padding: 20px 10px;
  }
  
  .card-header {
    .header-left {
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;
    }
  }
  
  .search-container {
    flex-direction: column;
    
    .search-button {
      width: 100%;
    }
  }
  
  .single-message-card {
    padding: 12px 16px;
    
    .message-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 4px;
    }
    
    .message-time {
      margin-left: 0;
    }
  }
  
  .message-detail-dialog {
    width: 90% !important;
    
    .detail-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;
      
      .message-actions {
        width: 100%;
        justify-content: flex-end;
      }
    }
  }
}
</style>